package org.jeecgframework.web.service.impl;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.SoftwareVersionServiceI;
import org.jeecgframework.web.system.pojo.base.SoftwareVersionEntity;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

@Service("softwareVersionService")
@Transactional
public class SoftwareVersionServiceImpl extends CommonServiceImpl implements SoftwareVersionServiceI {
    @Autowired
    private  SystemService systemService;

    public <T> void delete(T entity) {
        super.delete(entity);
        //执行删除操作配置的sql增强
        this.doDelSql((SoftwareVersionEntity) entity);
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save(entity);
        //执行新增操作配置的sql增强
        this.doAddSql((SoftwareVersionEntity) entity);
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate(entity);
        //执行更新操作配置的sql增强
        this.doUpdateSql((SoftwareVersionEntity) entity);
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @param id
     * @return
     */
    public boolean doAddSql(SoftwareVersionEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @param id
     * @return
     */
    public boolean doUpdateSql(SoftwareVersionEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @param id
     * @return
     */
    public boolean doDelSql(SoftwareVersionEntity t) {
        return true;
    }

    @Override
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        try {
            String fileName = "软件版本.xlsx";
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
            out = response.getOutputStream();
            String[] planIdsArr = oConvertUtils.getString(request.getParameter("id")).split(",");
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT\n");
            sql.append("\tid,\n");
            sql.append("\tsofe_name,\n");
            sql.append("\tzy_esitem_name,\n");
            sql.append("\tversion,\n");
            sql.append("\tversion_explain,\n");
            sql.append("\n");
            sql.append("IF (\n");
            sql.append("\tstate = '").append(1).append("',\n");
            sql.append("\tDATE_FORMAT(s.create_date, '%Y-%m-%d'),\n");
            sql.append("\tDATE_FORMAT(s.update_date, '%Y-%m-%d')\n");
            sql.append(") AS date,\n");
            sql.append("\tCASE state\n");
            sql.append("WHEN '").append(1).append("' THEN\n");
            sql.append("\t'已发布'\n");
            sql.append("WHEN '").append(2).append("' THEN\n");
            sql.append("\t'已升级'\n");
            sql.append("END AS state\n");
            sql.append("FROM\n");
            sql.append("\tcbs_software_version s\n");
            sql.append("WHERE");
            sql.append(" id IN ( ");
            for (int i = 0; i < planIdsArr.length; i++) {
                if (i == planIdsArr.length - 1) {
                    sql.append("'" + planIdsArr[i] + "'");
                } else {
                    sql.append("'" + planIdsArr[i] + "',");
                }
            }
            sql.append(" 	) ");

            List<Map<String, Object>> reusltMaps = super.findForJdbc(sql.toString());
            TSUser user = ResourceUtil.getSessionUserName();
            systemService.addLog(user.getRealName()+"导出"+reusltMaps.size()+"条软件版本记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

            InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/softwareVersion.xlsx");
            XSSFWorkbook xssf = new XSSFWorkbook(is);
            XSSFSheet sheet = xssf.getSheetAt(0);
            int rowNum = 1;
            for (Map<String, Object> dataMap : reusltMaps) {
                XSSFRow row = sheet.createRow(rowNum);
                int cellNum = 0, index = 0;
                for (String key : dataMap.keySet()) {
                    if (index == 0) {
                        index++;
                        continue;
                    }
                    XSSFCell cell = row.createCell(cellNum);
                    cell.setCellValue(dataMap.get(key) != null ? dataMap.get(key).toString() : "");
                    cellNum++;
                }
                rowNum++;
            }
            xssf.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, SoftwareVersionEntity t) {
        sql = sql.replace("#{id}", String.valueOf(t.getId()));
        sql = sql.replace("#{sofe_name}", String.valueOf(t.getSofeName()));
        sql = sql.replace("#{zy_esitem}", String.valueOf(t.getZyEsitem()));
        sql = sql.replace("#{zy_esitem_name}", String.valueOf(t.getZyEsitemName()));
        sql = sql.replace("#{version}", String.valueOf(t.getVersion()));
        sql = sql.replace("#{version_explain}", String.valueOf(t.getVersionExplain()));
        sql = sql.replace("#{state}", String.valueOf(t.getState()));
        sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
        sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
        sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
        sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
        sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
        sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
        sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
        return sql;
    }
}